package com.fc.happyteam.utils.validator.dictionary;


import com.fc.happyteam.entity.SysDictGroupEntity;
import com.fc.happyteam.entity.SysDictItemEntity;
import com.fc.happyteam.service.ISysDictService;
import com.fc.happyteam.utils.SpringContextUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class DictionaryValidator implements ConstraintValidator<Dictionary, String> {

    private ISysDictService sysDictService;
    private String[] codes;
    @Override
    public void initialize(Dictionary dictionary) {
        sysDictService = (ISysDictService)SpringContextUtils.getBean("sysDictService");
        codes = dictionary.codes();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if(s != null){
            Set<String> set = new HashSet<>();
            for(String code : codes){
                SysDictGroupEntity sysDictGroupEntity = sysDictService.getSysDictGroupByCode(code);
                List<SysDictItemEntity> sysDictItemEntities =  sysDictGroupEntity.getDictItemList();
                if(sysDictItemEntities != null){
                    for(SysDictItemEntity sysDictItemEntity : sysDictItemEntities){
                        set.add(sysDictItemEntity.getCode());
                    }
                }
            }
            String[] items = s.split(",");
            for(String item : items){
                if(!set.contains(item)){
                    return false;
                }
            }
            return true;
        }
        return false;
    }
}
